package me.jessyan.mvparms.demo.mvp.ui.fragment;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.Image;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;

import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;

import com.platform.ai.control.R;


import org.simple.eventbus.Subscriber;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import me.jessyan.mvparms.demo.di.component.DaggerUserComponent;
import me.jessyan.mvparms.demo.di.module.UserModule;
import me.jessyan.mvparms.demo.mvp.contract.UserContract;
import me.jessyan.mvparms.demo.mvp.model.entity.Device;
import me.jessyan.mvparms.demo.mvp.model.entity.MessageEvent;
import me.jessyan.mvparms.demo.mvp.model.entity.User;
import me.jessyan.mvparms.demo.mvp.model.logic.TextUtil;
import me.jessyan.mvparms.demo.mvp.presenter.UserPresenter;
import me.jessyan.mvparms.demo.mvp.ui.activity.MainActivity;
import me.jessyan.mvparms.demo.mvp.ui.activity.MediaService;
import me.jessyan.mvparms.demo.mvp.ui.adapter.LightMainAdapter;
import retrofit2.http.HEAD;

import static android.content.Context.BIND_AUTO_CREATE;


@SuppressLint("ValidFragment")
public class MusicFragment extends BaseFragment<UserPresenter> implements UserContract.View, SwipeRefreshLayout.OnRefreshListener, View.OnClickListener, SeekBar.OnSeekBarChangeListener {

    @BindView(R.id.playing_pre)
    ImageView playingPre;
    @BindView(R.id.playing_play)
    ImageView playingPlay;
    @BindView(R.id.playing_next)
    ImageView playingNext;
    @BindView(R.id.tv_music_label)
    TextView mMusicLabel;
    @BindView(R.id.music_seek_bar)
    SeekBar mMusicSeekBar;
    @BindView(R.id.tv_current_time)
    TextSwitcher mCurSwitcher;
    @BindView(R.id.tv_max_time)
    TextView mMaxSwitcher;
    boolean isPlaying = false;//0,1 判断是否处于播放状态
    private MediaPlayer mPlayer;

    public static MusicFragment newInstance() {
        MusicFragment fragment = new MusicFragment();
        return fragment;
    }

    public MusicFragment(){

    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
        DaggerUserComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .userModule(new UserModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_music, container, false);
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0){
                if(isPlaying) {
                    long musicDuration = mPlayer.getDuration();
                    final long position = mPlayer.getCurrentPosition();
                    final Date dateTotal = new Date(musicDuration);
                    final SimpleDateFormat sb = new SimpleDateFormat("mm:ss");
                    if (mMusicSeekBar != null) {
                        mMusicSeekBar.setMax((int) musicDuration);
                        mMusicSeekBar.setProgress((int) position);
                    }
                    mCurSwitcher.post(
                            new Runnable() {
                                @Override
                                public void run() {
                                    Date date = new Date(position);
                                    String time = sb.format(date);
                                    mCurSwitcher.setCurrentText(time);
                                    mMaxSwitcher.setText(sb.format(dateTotal));
                                }
                            }
                    );
                }
            }
        }
    };
    private final Timer timer = new Timer();
    @Override
    public void initData(Bundle savedInstanceState) {
        initRecycleView();
        TimerTask mTimerTask = new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(0);
            }
        };
        timer.schedule(mTimerTask, 0, 1000);;
    }

    @Override
    public void onPause() {
        super.onPause();
        pause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void killMyself() {
        pause();
        mPlayer.release();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        pause();

    }

    @Override
    public void onStop() {
        super.onStop();
        pause();

    }

    @Override
    public void setData(Object data) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        if (!message.isEmpty()) {

        }
    }

    @Override

    public void launchActivity(@NonNull Intent intent) {

    }

    @Override
    public void setAdapter(DefaultAdapter adapter) {

    }

    @Override
    public void loginReturn(User user) {

    }

    @Override
    public void logout() {

    }


    public void uploadResult(String string) {

    }

    @Override
    public void onRefresh() {
        requestData();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.playing_pre://前一曲
                playPre();
                break;
            case R.id.playing_play://播放中
                if (isPlaying){
                    pause();
                }else {
                    playing();
                }
                break;
            case R.id.playing_next://下一曲
                playNext();
                break;
            default:
                break;
        }

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mPlayer.pause();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
            public void onSeekComplete(MediaPlayer m) {
                mPlayer.start();
            }
        });
        mPlayer.seekTo(seekBar.getProgress());

    }

    @Subscriber
    public void onMessageEvent(MessageEvent event) {
        if(event.getMessage().equals("update")){
            requestData();
        }
    }

    private void initRecycleView() {
        playingPre.setOnClickListener(this);
        playingPlay.setOnClickListener(this);
        playingNext.setOnClickListener(this);
        mMusicSeekBar.setOnSeekBarChangeListener(this);
        mMusicLabel.setText(MainActivity.MUSIC_LABEL);
        playing();
    }

    public void requestData() {
        mPlayer.release();
        mMusicLabel.setText(MainActivity.MUSIC_LABEL);
        playingPlay.setImageResource(R.mipmap.icon_pause);
        if (!TextUtil.isEmpty(MainActivity.MUSIC_URL)) {
            mPlayer = MediaPlayer.create(mContext, Uri.parse(MainActivity.MUSIC_URL));
        } else {
            mPlayer = MediaPlayer.create(mContext, R.raw.spz);
        }
        playing();

    }
    //播放：1、播放音乐 2、动画旋转 3、暂停图片切换为播放按钮图片
    private void pause(){
        isPlaying = false;
        mMusicLabel.setText(MainActivity.MUSIC_LABEL);
        playingPlay.setImageResource(R.mipmap.icon_playing);
        mPlayer.pause();
    }

    public void playPre(){
        pause();
        if(mPlayer != null) {
            mPlayer.release();
            if (MainActivity.MUSIC_LABEL.equals("生僻字")) {
                MainActivity.MUSIC_LABEL = "口是心非";
                mPlayer = MediaPlayer.create(mContext, R.raw.ksxf);
            } else if (MainActivity.MUSIC_LABEL.equals("稻香")) {
                MainActivity.MUSIC_LABEL = "生僻字";
                mPlayer = MediaPlayer.create(mContext,R.raw.spz);
            } else if (MainActivity.MUSIC_LABEL.equals("口是心非")) {
                MainActivity.MUSIC_LABEL = "稻香";
                mPlayer = MediaPlayer.create(mContext, R.raw.dx);
            }else{
                mPlayer = MediaPlayer.create(mContext, R.raw.ksxf);
            }
        }else{
            mPlayer = MediaPlayer.create(mContext, R.raw.ksxf);
        }
        playing();
    }

    public void playNext(){
        pause();
        if(mPlayer != null) {
            mPlayer.release();
            if (MainActivity.MUSIC_LABEL.equals("生僻字")) {
                MainActivity.MUSIC_LABEL = "稻香";
                mPlayer = MediaPlayer.create(mContext, R.raw.dx);
            } else if (MainActivity.MUSIC_LABEL.equals("稻香")) {
                MainActivity.MUSIC_LABEL = "口是心非";
                mPlayer = MediaPlayer.create(mContext, R.raw.ksxf);
            } else if (MainActivity.MUSIC_LABEL.equals("口是心非")) {
                MainActivity.MUSIC_LABEL = "生僻字";
                mPlayer = MediaPlayer.create(mContext, R.raw.spz);
            }
        }else{
            mPlayer = MediaPlayer.create(mContext,R.raw.dx);
        }
        playing();
    }

    //播放：1、播放音乐 2、动画旋转 3、暂停图片切换为播放按钮图片
    private void playing(){
        isPlaying = true;
        mMusicLabel.setText(MainActivity.MUSIC_LABEL);
        playingPlay.setImageResource(R.mipmap.icon_pause);
        if(mPlayer == null) {
            mMusicLabel.setText(MainActivity.MUSIC_LABEL);
            playingPlay.setImageResource(R.mipmap.icon_pause);
            if (!TextUtil.isEmpty(MainActivity.MUSIC_URL)) {
                mPlayer = MediaPlayer.create(mContext, Uri.parse(MainActivity.MUSIC_URL));
            } else {
                mPlayer = MediaPlayer.create(mContext, R.raw.spz);
            }
        }
        mPlayer.start();//开启音乐
    }


}
